﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Huirui.Cavan.Domain.Seedwork;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Application.Seedwork;
using Huirui.Cavan.Domain.MainBoundedContext.StockModule;
using Huirui.Cavan.Application.MainBoundedContext.SystemModule;
using Spring.Context.Support;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;
using Huirui.Cavan.Domain.MainBoundedContext.ReportModule;
namespace Huirui.Cavan.Application.MainBoundedContext.StockModule
{
    public class StockTypeAppService : BaseAppService<StockType, StockTypeSearch, IStockTypeRepository>, IStockTypeAppService
    {
        public override BoolGenericResult<StockType> AddOrUpdate(StockType entity)
        {
            Init();
 
            BoolGenericResult<StockType> result = new BoolGenericResult<StockType>();
            if (entity.IsNull())
            {
                throw new ArgumentNullException("");
            }
            Employee employee = this.EmployeeAppService.GetBySearch(SearchFactory.CreateEmployeeSearch(SecurityAppService.UserAccount.Id)).FirstOrDefault();
            StockManager stockManager = new StockManager(employee);

            StockType oldStock = null;
            if (entity.Id !=0 )
            {
                oldStock = this.Repository.Get(entity.Id);
            }
            if (oldStock.IsNull())
            {
                IIDGenerateAppService idGenerateAppService = this.SpringContext.GetObject(SystemModuleConst.IDGENERATEAPPSERVICE, new object[] { employee.Corporation }) as IIDGenerateAppService;
                
                result = stockManager.AddStockType(entity.Name,entity.EditUser);
                if (result.IsSuccess)
                    return base.Add(result.Object);
            }
            else
            {
                result = stockManager.UpdateStockType(oldStock,entity.Name,entity.EditUser);
                if (result.IsSuccess)
                    return base.Update(result.Object);
            }
            return result;
        }

    }
}
